/**
 * 页面（页面肩部）级别按钮click事件
 */
import { print, promptBox, toast, ajax ,pageTo,cacheTools} from 'nc-lightapp-front';

import requestApi, { isUploadedAttachments } from '../requestApi'
import {imageScan, imageView} from "sscrp/rppub/components/image";
import presetVar from '../presetVar';
import linkVoucherApi from '../../../../public/components/linkvoucher/linkvoucher'
import linkBudgetApi from '../../../../public/components/linkbudget/linkbudget'
import {setFormData, updataFormData, setcardTableData, updatacardTableData} from 'ssccommon/utils/changePageData';
import {routeChange} from '../initTemplate';
import { viewModel } from 'nc-lightapp-front';

let { getGlobalStorage } = viewModel;


const pageButton = presetVar.pageButton;
const statusVar = presetVar.status;
const head1 = presetVar.head.head1;
const body1 = presetVar.body.body1;
const pageId = presetVar.pageId;
const pageCode = presetVar.pageCode;
let ntbCheck = 'false';


function pageButtonClick() {
    let props = this.props;
    function setBillData(data, updataAll) {
        // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
        // props.form.setAllFormValue({ [head1]: data.head[head1] }); 
        // //设置表体数据
        // Object.values(presetVar.body).forEach((body) => {
        //     if (data.bodys[body]) {
        //         props.cardTable.setTableData(body, data.bodys[body]);
        //     }
        // });

        if(updataAll){
            setFormData(props, head1, data.head[head1]);
            //设置表体数据
            Object.values(presetVar.body).forEach((body) => {
                if (data.bodys[body]) {
                    setcardTableData(props, body, data.bodys[body]);
                }
            });
        }else{
            updataFormData(props, head1, data.head[head1]);
            //设置表体数据
            Object.values(presetVar.body).forEach((body) => {
                if (data.bodys[body]) {
                    updatacardTableData(props, body, data.bodys[body]);
                }
            });
        }
        // BTM 性能优化，变更页面数据更新方法
    }

    async function submitAndSaveSubmit() {
        let checkResult = props.form.isCheckNow(head1) && props.cardTable.checkTableRequired();
        if(checkResult){
            //校验附件是否必须上传
            const is_uploaded = await isUploadedAttachments.call(this, props)
            if(!is_uploaded) return 

            let billdata = props.createExtCardData(presetVar.nccPageCode, head1, [body1]);
            for (let bodyArea in billdata.bodys) {
                //不传递删除的行。后台是批量保存，不会根据状态排除掉删除的行
                billdata.bodys[bodyArea].rows = props.cardTable.getVisibleRows(bodyArea);
            }
            let multiLang = props.MutiInit.getIntl(2011); //this.moduleId
            let send_data = {};
            let jeIsNull = billdata.bodys[body1].rows.some((row) => {
                return +row.values.assume_amount.value == 0
            })
            if (jeIsNull) {
                promptBox({
                    color: 'danger',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                    content: multiLang && multiLang.get('201102SQFY-0034'),//'表体行金额不能为0',             // 提示内容,非必输
                    noCancelBtn: true,             // 是否显示取消按钮,，默认显示(false),非必输
                    beSureBtnName: multiLang && multiLang.get('2011-0003'),//"确定",          // 确定按钮名称, 默认为"确定",非必输
                })
                return;
            }
    
            let paramdata = {};
            paramdata.pagecode = presetVar.nccPageCode;
            paramdata.appcode = presetVar.nccAppCode;
            
            paramdata.accessorybillid = presetVar.openBillId;
            paramdata.fromssc = "ssc",
                paramdata.jkCheck = "true",
                paramdata.ntbCheck = ntbCheck,
                paramdata.msg_pk_bill = "",
                paramdata.pk_tradetype = presetVar.tradeType;
            paramdata.assingUsers = window.assingUsers;
            let status = this.props.getUrlParam("status");
            if(status != "add"){
                paramdata.openbillid = presetVar.openBillId;
            }
            if (status == "edit") {
                paramdata.status = "edit";
            }  else if (status =="browse"){
                paramdata.status = "browse";
            }else {
                paramdata.status = "save";
            }
            //如果指派点了确定  由于第一次点击保存提交实际上已经保存成功了，指派后再次提交应该走浏览提交逻辑
            if(window.sureAssign){
                paramdata.status = "edit";
                paramdata.openbillid = window.assignBillId;
            }
            billdata.head.userjson = JSON.stringify(paramdata);
            send_data = { billdata, paramdata };
			// TOP NCCLOUD-91597 校验报销标准取模板时需要使用模板ID chengwbc ADD
			billdata.templetid = this.props.meta.getMeta().pageid;
			// BTM NCCLOUD-91597 校验报销标准取模板时需要使用模板ID
            requestApi.submitBill({
                data: billdata,
                success: (data) => {
                    //设置了指派指派
                    if (data.workflow && data.billid && data.bill && (data.workflow == 'approveflow' || data.workflow == 'workflow')) {
                        this.setState({
                            compositedata: data,
                            compositedisplay: true
                        });
                        window.assignBillId = data.billid;
                        //设置表头数据
                        updataFormData(props, head1, data.bill.head[head1]);
                        //设置表体数据
                        data.bill.body && updatacardTableData(props, body1, data.bill.body[body1]);
                    } else {
                        this.setState({
                            compositedisplay: false
                        });
                        if (data['bugetAlarm']) {
                            promptBox({
                                color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                title: multiLang && multiLang.get('201102JCLF_C-0002'),//"提示信息"
                                content: (multiLang && multiLang.get('201102JCLF_C-0003')) + data['bugetAlarm'] + (multiLang && multiLang.get('201102JCLF_C-0004')),
                                noFooter: false,  // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                noCancelBtn: false,    // 是否显示取消按钮,，默认显示(false),非必输
                                beSureBtnName: multiLang && multiLang.get('2011-0003'),
                                cancelBtnName: multiLang && multiLang.get('2011-0002'),
                                beSureBtnClick: () => {
                                    ntbCheck = 'true';
                                    pageButtonClick.call(this)[pageButton.Submit]();
                                },
                                cancelBtnClick: () => {
                                    let billdata =  props.createExtCardData(presetVar.nccPageCode, head1, [body1]);
                                    let headValues = billdata.head[head1].rows[0].values;
                                    let billid = headValues.pk_jkbx.value;
                                    if(props.getUrlParam('status') === 'browse'){
                                        pageTo.specialLinkTo(location.pathname, {
                                            status: statusVar.browse,
                                            id: billid,
                                            fromBillAction: 'submit_' + new Date().getTime(),
                                            scene: presetVar.scene
                                        })
                                        routeChange.call(this, this.props)
                                    }else{
                                        if(billid){
                                            pageTo.specialLinkTo(location.pathname, {
                                                status: statusVar.edit,
                                                id: billid,
                                                fromBillAction: 'submit_' + new Date().getTime(),
                                                scene: presetVar.scene
                                            })
                                        }else{
                                            pageTo.specialLinkTo(location.pathname, {
                                                status: statusVar.add,
                                                fromBillAction: 'submit_' + new Date().getTime(),
                                                scene: presetVar.scene
                                            })
                                        }
                                        routeChange.call(this, this.props)
                                }

                                    window.assingUsers = [];    //清空指派人信息
                                    window.sureAssign = false;
                                }
                            })
                        } else {
                            setBillData(data);
    
                            let billid = data.head[head1].rows[0].values.pk_jkbx.value;
                            window.assingUsers = [];
                            pageTo.specialLinkTo(location.pathname, {
                                status: statusVar.browse,
                                id: billid,
                                fromBillAction: 'submit_' + new Date().getTime(),
                                scene: presetVar.scene
                            })
                            routeChange.call(this, this.props)
                        }
                    }
                },
                error: (data) => {
                    toast({ content: data.message, color: 'danger' });
                }
            });
        }
    }

    return {
        //提交
        [pageButton.Submit]: () => {
            submitAndSaveSubmit.call(this);
        },
        //保存提交
        [pageButton.SaveSubmit]: () => {
            let billdataForFormula = props.createMasterChildData(presetVar.nccPageCode, head1, body1);
            props.validateToSave(billdataForFormula, () => {
                submitAndSaveSubmit.call(this);
            }, body1, null)
        },
        //保存
        [pageButton.Save]: async () => {
            props.cardTable.filterEmptyRows(body1, ['assume_amount'], 'include');
            let checkResult = props.form.isCheckNow(head1) && props.cardTable.checkTableRequired();
            if(checkResult){
                //校验附件是否必须上传
                const is_uploaded = await isUploadedAttachments.call(this, props)
                console.log('xxx:', is_uploaded)
                if(!is_uploaded) return 

                //后台是一主多子设计。需要用createExtCardData生成的数据结构
                let billdata = props.createExtCardData(presetVar.nccPageCode, head1, [body1]);
                //前台呈现是一主一子的结构。需要用createMasterChildData生成的数据结构，否则calidateToSave不能带回表体的公式。
                let billdataForFormula = props.createMasterChildData(presetVar.nccPageCode, head1, body1);
                for (let bodyArea in billdata.bodys) {
                    props.cardTable.closeModel(bodyArea);
                }
                props.validateToSave( billdataForFormula , () => {
                    let jeIsNull = billdata.bodys[body1].rows.some((row) => {
                        return +row.values.assume_amount.value == 0
                    })
                    if (jeIsNull) {
                        promptBox({
                            color: 'danger',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                            content: '表体行金额不能为0',             // 提示内容,非必输
                            noCancelBtn: true,             // 是否显示取消按钮,，默认显示(false),非必输
                            beSureBtnName: "确定",          // 确定按钮名称, 默认为"确定",非必输
                        })
                        return;
                    }
                    
    
                    let paramdata = {};
                    paramdata.pagecode = presetVar.nccPageCode;
                    paramdata.appcode = presetVar.nccAppCode;
                    paramdata.fromssc = "ssc";
                    paramdata.jkCheck = "true";
                    paramdata.ntbCheck = ntbCheck;
                    paramdata.msg_pk_bill = "";
                    paramdata.accessorybillid = this.accessorybillid;
                    paramdata.pk_tradetype = presetVar.tradeType;
                    paramdata.status = presetVar.pageStatus;
                    paramdata.accessorybillid = presetVar.openBillId;
                    billdata.head.userjson = JSON.stringify(paramdata);
    
                    //不传递删除的行。后台是批量保存，不会根据状态排除掉删除的行
                    for (let bodyArea in billdata.bodys) {
                        billdata.bodys[bodyArea].rows = props.cardTable.getVisibleRows(bodyArea);
                    }
                    let vat_amount = props.form.getFormItemsValue(head1,"total").value;
                        if(vat_amount==undefined||vat_amount==null){
                            toast({content:multiLang && multiLang.get('201102FYYT-0019')/*"金额不能为空!"*/,color:'warning'});
                            return;
                        }
					// TOP NCCLOUD-91597 校验报销标准取模板时需要使用模板ID chengwbc ADD
					billdata.templetid = props.meta.getMeta().pageid;
                    // BTM NCCLOUD-91597 校验报销标准取模板时需要使用模板ID
                    let multiLang = props.MutiInit.getIntl(2011); //this.moduleId
                    requestApi.savejkbx({
                        data: billdata,
                        success: (data) => {
                            if (data['bugetAlarm']) {
                                promptBox({
                                    color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                    title: multiLang && multiLang.get('201102JCLF_C-0002'),//"提示信息"
                                    content: (multiLang && multiLang.get('201102JCLF_C-0003')) + data['bugetAlarm'] + (multiLang && multiLang.get('201102JCLF_C-0004')),
                                    noFooter: false,  // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                    noCancelBtn: false,    // 是否显示取消按钮,，默认显示(false),非必输
                                    beSureBtnName: multiLang && multiLang.get('2011-0003'),
                                    cancelBtnName: multiLang && multiLang.get('2011-0002'),
                                    beSureBtnClick: () => {
                                        ntbCheck = 'true';
                                        pageButtonClick.call(this)[pageButton.Save]();
                                    }
                                    //cancelBtnClick: functionCancel  // 取消按钮点击调用函数,非必输
                                })
                            }else{
                                setBillData(data);
                                let billid = data.head[head1].rows[0].values.pk_jkbx.value;
                                pageTo.specialLinkTo(location.pathname, {
                                    status: statusVar.browse,
                                    id: billid,
                                    scene: presetVar.scene
                                });
                                routeChange.call(this, this.props)
                                ntbCheck = 'false';
                            }
                        },
                        error: (data) => {
                            /* debugger;
                            promptBox({
                                color: 'danger',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                content: '显示内容',             // 提示内容,非必输
                                noFooter: false,                // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                beSureBtnName: "确定",          // 确定按钮名称, 默认为"确定",非必输
                            }) */
    
                        }
                    });
                } , body1 , null )
            }
        },
        [pageButton.Recall]: () => {
            requestApi.billRecall({
                data: {
                    openbillid: presetVar.openBillId,
                    pagecode: presetVar.nccPageCode
                },
                success: (data) => {
                    if (data.success) {
                        setBillData(data.data);
                        pageTo.specialLinkTo(location.pathname, {
                            status: statusVar.browse,
                            id: presetVar.openBillId,
                            fromBillAction: 'recall_' + new Date().getTime(),
                            scene: presetVar.scene
                        })
                        routeChange.call(this, this.props)
                        ntbCheck = 'false';
                    }
                }
            })
        },
        [pageButton.Edit]: () => {
            let props = this.props;
            let multiLang = this.props.MutiInit.getIntl(2011);
            let scene = props.getUrlParam('scene');
            //获取单据编号
            let djbh = props.form.getFormItemsValue(head1,['djbh'])[0].value;
            let canEdit = true;
            let isMaker = true;
            //来源于审批中心
            if(scene == 'approve'  || scene == 'approvesce' ){
                isMaker = false;
                //判断单据是否是当前用户待审批
                ajax({
                    url: '/nccloud/riart/message/list.do',
                    async: false,
                    data: {
                        billno: djbh,
                        isread:'N'
                    },
                    success: result => {
                        if(result.data) {
                            if(result.data.total < 1){
                                toast({content:multiLang&&multiLang.get('201102SQFY-0027')/**"当前单据已审批，不可进行修改操作!"**/,color:'warning'});
                                canEdit =false;
                            }
                        }
                    }
                });
            }
            //来源于我的作业
            if(scene == 'zycl'){
                isMaker = false;
                //判断单据是否是当前用户待处理
                ajax({
                    url: '/nccloud/ssctp/sscbd/SSCTaskHandlePendingNumAction.do',
                    async: false,
                    data: {
                        billno: djbh
                    },
                    success: result => {
                        if(result.data) {
                            if(result.data.total < 1){
                                toast({content:multiLang&&multiLang.get('201102SQFY-0028')/*"当前单据已处理，不可进行修改操作!"*/,color:'warning'});
                                canEdit =false;
                            }
                        }
                    }
                });
            }

            //特殊数据权限校验
            ajax({
                url: '/nccloud/erm/pub/ErmBillEditAction.do',
                async: false,
                data: {
                    'pk_org': props.form.getFormItemsValue(head1,['pk_org'])[0].value,
                    'billid': props.form.getFormItemsValue(head1,['pk_jkbx'])[0].value,
                    'billType':props.form.getFormItemsValue(head1,['djlxbm'])[0].value
                },
                success: result => {
                    
                },
                error: (data) => {
                    canEdit = false;
                    toast({ content: data.message, color: 'danger' });
                }
            });

            if(!canEdit){
                return;
            }

            if(isMaker){
                //驳回不重走流程单据，设置不可编辑字段
                requestApi.getUnEditAttributes({
                    data: {
                        'pk_org': props.form.getFormItemsValue(head1,['pk_org'])[0].value,
                        'billid': props.form.getFormItemsValue(head1,['pk_jkbx'])[0].value,
                        'billType':props.form.getFormItemsValue(head1,['djlxbm'])[0].value
                    },
                    success: (data) => {
                        if(!(data==undefined || data.length == 0)){
                            let formobj = {};
                            let er_cshare_detailobj = [];

                            data.forEach((item) => {
                                if(item.indexOf('costsharedetail.')>-1){
                                    er_cshare_detailobj.push(item.split('.')[1]);
                                }else{
                                    formobj[item] = true;
                                }
                            })
                            props.form.setFormItemsDisabled(head1,formobj)
                            props.cardTable.setColEditableByKey('er_cshare_detail',er_cshare_detailobj)
                        }
                    }
                })
            } else {
                 //除制单人环节外的可编辑属性
                 requestApi.getUnEditAttributes({
                    data: {
                        'pk_org': props.form.getFormItemsValue(head1,['pk_org'])[0].value,
                        'billid': props.form.getFormItemsValue(head1,['pk_jkbx'])[0].value,
                        'billType':props.form.getFormItemsValue(head1,['djlxbm'])[0].value
                    },
                    success: (data) => {
                        if(!(data==undefined || data.length == 0)){
                            let formobj = {};
                            let er_cshare_detailobj = [];

                            data.forEach((item) => {
                                if(item.indexOf('costsharedetail.')>-1){
                                    er_cshare_detailobj.push(item.split('.')[1]);
                                }else{
                                    formobj[item] = false;
                                }
                            })
                            props.form.setFormItemsDisabled(head1,formobj)
                            props.cardTable.setColEditableByKey('er_cshare_detail',er_cshare_detailobj,false)
                        }
                    }
                })
            }

            pageTo.specialLinkTo(location.pathname, {
                status: statusVar.edit,
                id: presetVar.openBillId,
                scene: presetVar.scene
            })
            routeChange.call(this, this.props)
        },
        [pageButton.Copy]: () => {
            pageTo.specialLinkTo(location.pathname, {
                status: statusVar.add,
                copyFromBillId: presetVar.openBillId,
                scene: presetVar.scene
            })
            routeChange.call(this, this.props)
            window.assingUsers=[];
             //复制出来的单据要先清空附件产生的单据pk
             this.accessorybillid = '';
             this.setState({ billId: ''});
             let multiLang = this.props.MutiInit.getIntl(2011);
             this.props.button.setButtonTitle('File', multiLang&&multiLang.get('201102TZFY-0003')/**'附件'**/ + ' ' + 0 + ' ');

        },
        [pageButton.Delete]: () => {//删除单据
            requestApi.billRemove({
                data: {
                    openbillid: presetVar.openBillId
                },
                success: (data) => {
                    if (data.success) {
                        window.onbeforeunload=null;
                        window.top.close();
                    }
                }
            });
        },
        [pageButton.Invalid]: () => {//单据作废
            let multiLang = this.props.MutiInit.getIntl(2011); 
            let props = this.props;
            requestApi.billInvalid({
                data: {
                    openbillid: presetVar.openBillId,
                    tradetype: presetVar.tradeType,
                    pagecode: presetVar.nccPageCode
                },
                success: (data) => {
                    if (data.success) {
                        toast({color:'success', title: multiLang&&multiLang.get('201102TZFY-0004')/*'单据作废成功！'*/})
                        setBillData(data.data);
                        pageTo.specialLinkTo(location.pathname,
                            {
                                status: statusVar.browse,
                                id: presetVar.openBillId,
                                formBillAction: 'invalid_' + new Date().getTime(),
                                scene: presetVar.scene
                            })
                        routeChange.call(this, this.props)
                    }


                    //location.hash = `#status=${statusVar.browse}&billId=${props.form.getFormItemsValue(presetVar.head.head1, 'billno').value}`;
                }
            });
        },
        [pageButton.Enable]: () => { //单据重启
            let props = this.props;
            props.form.setFormStatus(head1, statusVar.browse);
            props.cardTable.setStatus(body1, statusVar.browse);
            let allData = props.createMasterChildData(pageId, head1, body1);
            requestApi.billEnable({
                data: allData,
                success: (data) => {
                    // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                    // //设置表头数据
                    // props.form.setAllFormValue({ [head1]: data.data.head[head1] })
                    // //设置表体数据
                    // data.data.body && this.props.cardTable.setTableData(body1, data.data.body[body1]);
                    //设置表头数据
                    updataFormData(props, head1, data.data.head[head1]);
                    //设置表体数据
                    data.data.body && updatacardTableData(props, body1, data.data.body[body1]);
                    // BTM 性能优化，变更页面数据更新方法
                    //location.hash = `#status=${statusVar.browse}&billId=${props.form.getFormItemsValue(presetVar.head.head1, 'billno').value}`;
                }
            });
        },
        [pageButton.Close]: () => {//单据关闭
            let props = this.props;
            props.form.setFormStatus(head1, statusVar.browse);
            props.cardTable.setStatus(body1, statusVar.browse);
            let allData = props.createMasterChildData(pageId, head1, body1);
            requestApi.billClose({
                data: allData,
                success: (data) => {
                    // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                    // //设置表头数据
                    // props.form.setAllFormValue({ [head1]: data.data.head[head1] })
                    // //设置表体数据
                    // data.data.body && this.props.cardTable.setTableData(body1, data.data.body[body1]);
                    //设置表头数据
                    updataFormData(props, head1, data.data.head[head1]);
                    //设置表体数据
                    data.data.body && updatacardTableData(props, body1, data.data.body[body1]);
                    // BTM 性能优化，变更页面数据更新方法
                    //location.hash = `#status=${statusVar.browse}&billId=${props.form.getFormItemsValue(presetVar.head.head1, 'billno').value}`;
                }
            });
        },
        [pageButton.Cancel]: async () => {
            const copyBillId = props.getUrlParam('copyFromBillId')
            let billId = presetVar.openBillId || props.getUrlParam('copyFromBillId');
            if(copyBillId)  {
                billId = copyBillId
            }
            if (billId && (presetVar.pageStatus == presetVar.status.edit || presetVar.pageStatus == presetVar.status.add)) { //复制单据后退的时候是add状态

                //提交校验附件是否必须上传
                // const is_uploaded = await isUploadedAttachments.call(this, props)
                // if(!is_uploaded) return  

                let billdata = {};
                billdata.openbillid = billId;
                billdata.tradetype = presetVar.tradeType;
                billdata.pagecode = presetVar.nccPageCode;
                requestApi.viewBill({
                    data: billdata,
                    success: (data) => {
                        props.form.setAllFormValue({ [presetVar.head.head1]: data.head[presetVar.head.head1] });
                        //设置表体数据
                        Object.values(presetVar.body).forEach((body) => {
                            if (data.bodys[body]) {
                                props.cardTable.setTableData(body, data.bodys[body]);
                            }
                        });
                        pageTo.specialLinkTo(location.pathname, {
                            status: statusVar.browse,
                            id: billId,
                            fromBillAction: 'edit_back_' + new Date().getTime(),
                            scene: presetVar.scene
                        })
                        routeChange.call(this, this.props)
                    }
                });
                
            } else {
                window.onbeforeunload=null;
                window.top.close();
            }
        },
        [pageButton.Print]: () => {//打印单据
            let vdata = {};
            vdata.billId = presetVar.openBillId;
            vdata.billType = presetVar.tradeType;
            ajax({
                url: '/nccloud/erm/expenseaccount/ErmPrintValidaAction.do',
                data: vdata,
                success: (data) => {
                    if (!data.data.canPrint){
                        promptBox({
                            color: 'danger',
                            content: data.data.errMesg, 
                            noCancelBtn: true,             
                            beSureBtnName: "确定",
                        })
                    }else {
                        print(
                            'pdf',  //支持两类: 'html'为模板打印, 'pdf'为pdf打印
                            '/nccloud/erm/expenseaccount/ErmJkbxPrintAction.do', //后台服务url
                            {
                                billtype:presetVar.tradeType,  //单据类型
                                funcode:(props.getUrlParam("appcode")==undefined||props.getUrlParam("appcode")=='')?props.getSearchParam("c"):props.getUrlParam("appcode"),   //功能节点编码，即模板编码
                                nodekey:'264a_WEB',     //模板节点标识
                                oids:[props.getUrlParam('id')]    // 功能节点的数据主键   oids含有多个元素(['1001A41000000000A9LR','1001A410000000009JDD'])时为批量打印,
                            }
                        )
                    }
                }
            })
        },
        [pageButton.ImageUpload]: () => {//影像扫描
            let props = this.props;
            let openbillid = props.getUrlParam('id');
            let billdata =  props.createExtCardData(presetVar.nccPageCode, head1, [body1]);

            let headValues = billdata.head[head1].rows[0].values;
            var billInfoMap = {};

            //基础字段 单据pk,单据类型，交易类型，单据的组织
            billInfoMap.pk_billid = openbillid;
            billInfoMap.pk_billtype = headValues.pk_billtype.value;
            billInfoMap.pk_tradetype = presetVar.tradeType;
            billInfoMap.pk_org = headValues.pk_org.value;

            //影像所需 FieldMap
            billInfoMap.BillType = presetVar.tradeType;
            billInfoMap.BillDate = headValues.creationtime.value;
            billInfoMap.Busi_Serial_No = headValues.pk_jkbx.value; //openbillid
            billInfoMap.pk_billtype = headValues.pk_billtype.value;
            billInfoMap.OrgNo = headValues.pk_org.value;
            billInfoMap.BillCode = headValues.djbh.value;  //单据号
            billInfoMap.OrgName = headValues.pk_org.display;
            billInfoMap.Cash = headValues.total.value; //合计金额

            console.log("billInfoMap",billInfoMap);
            imageScan(billInfoMap, 'iweb');
        }
        ,
        [pageButton.ImageShow]: () => {//影像查看
            let props = this.props;
            let openbillid = props.getUrlParam('id');
            let billdata = props.createExtCardData(presetVar.nccPageCode, head1, [body1]);
            let headValues = billdata.head[head1].rows[0].values;

            var billInfoMap = {};
            //基础字段 单据pk,单据类型，交易类型，单据的组织
            billInfoMap.pk_billid = openbillid;
            billInfoMap.pk_billtype = headValues.pk_billtype.value;
            billInfoMap.pk_tradetype = presetVar.tradeType;
            billInfoMap.pk_org = headValues.pk_org.value;

            console.log("billInfoMap",billInfoMap);
            imageView(billInfoMap,  'iweb');
        }
        ,
        [pageButton.File]: () => {//附件管理
            if (!presetVar.openBillId) {
                //去后台生成单据主键
                requestApi.generatBillId({
                    data: { billtype: presetVar.tradeType },
                    success: (data) => {
                        let accessorypkfildname = data["pkfieldName"];
                        presetVar.openBillId = data[accessorypkfildname];
                        this.setState({
                            showUploader: !this.state.showUploader
                        });
                    },
                    error: (data) => {
                        toast({ content: data.message, color: 'danger' });
                    }
                });
            } else {
                this.setState({
                    showUploader: !this.state.showUploader
                });
            }
        },
        [pageButton.LinkApprovalDetail]: () => {
            let props = this.props;
            let billdata = props.createMasterChildData(pageId, head1, body1);
            let pk_billtype = billdata.head[head1].rows[0].values.djlxbm.value;
            let billId = billdata.head[head1].rows[0].values.pk_jkbx.value || props.getUrlParam('id') || this.state.billId || "";
            this.setState({
                ShowApproveDetail: true,
                billId: billId,
                billtype: pk_billtype
            });
        },
        [pageButton.LinkVoucher]:() => {
            let multiLang = this.props.MutiInit.getIntl(2011);
            let billdata = props.createMasterChildData(pageId, head1, body1);
            let paramurl = getRequest1(parent.window.location.hash);
            //如果没取到应用主键再取一下外层,主要适配作业任务打开单据时联查凭证
            if(!paramurl.ar){
                paramurl = getRequest1(parent.parent.window.location.hash);
            }
            if(paramurl.ar){
                if (billdata.head[head1].rows.length){
                    let headValues = billdata.head[head1].rows[0].values;
                    linkVoucherApi.link({
                        data  : {
                            props : props,
                            record : {
                                pk_billtype : headValues.djlxbm.value,
                                pk_group : headValues.pk_group.value,
                                pk_org : headValues.pk_org.value,
                                relationID : headValues.pk_jkbx.value
                            },
                            appid : paramurl.ar
                        }
                    })
                }
            }else{
                toast({ content: multiLang&&multiLang.get('201102SQFY-0030')/*'联查凭证失败，缺少应用主键'*/, color: 'danger' });
            }
        },
        [pageButton.LinkBudget]:() => {
            let billdata = props.createMasterChildData(pageId, head1, body1);
            if (billdata.head[head1].rows.length){
                let headValues = billdata.head[head1].rows[0].values;
                linkBudgetApi.link({
                    data : {
                        "tradetype": headValues.djlxbm.value,
                        "openbillid" : headValues.pk_jkbx.value
                    },
                    success: (data) => {
                        this.setState({
                            sourceData: data,
                            showLinkBudget: true
                        })
                    }
                })
            }
        },
        [pageButton.Relation]:() => {
            let billdata =  props.createExtCardData(presetVar.nccPageCode, head1, [body1]);
            let headValues = billdata.head[head1].rows[0].values;

            window.billinfo.tzd_billid = headValues.pk_jkbx.value;
            window.billinfo.tzd_tradetype = headValues.djlxbm.value;
            window.billinfo.tzd_billno = headValues.djbh.value;

            this.setState({ showRelationModal: true });
        },
        [pageButton.LinkRelationBill]:() => {
            props.createUIDom(
                {
                    appcode: "201102TZFY",//小应用编码
                    pagecode: "201102LCDJ"//页面编码
                },
                (data) => {
                    let meta = props.meta.getMeta();
                    meta['linkrelationbill'] = data.template['rplist'];
                    props.meta.addMeta(meta);

                    
                    let billdata =  props.createExtCardData(presetVar.nccPageCode, head1, [body1]);
                    let headValues = billdata.head[head1].rows[0].values;
                    requestApi.linkRelationBill({
                        data : {
                            "tzd_billid" : headValues.pk_jkbx.value,
                            "actiontype" : "linkrelationbill"
                        },
                        success: (data) => {
                            if (!data.grid) {
                                this.props.table.setAllTableData('linkrelationbill', {rows:[]});
                            } else {
                                this.props.table.setAllTableData('linkrelationbill', data.grid.rplist);
                            }
                        }
                    })
                })

            this.setState({ linkRelationBillModal: true });
        },
        //制单按钮逻辑
        [pageButton.pageMakebill]: () => {
            let props = this.props;
            let pk_accrued_bill=props.form.getFormItemsValue("head","pk_jkbx").value;//表头的单据主键
            let pk_tradetype=props.form.getFormItemsValue("head","djlxbm").value;//单据类型编码
            //后台接口业务参数
            let makebillArr = {
                "pk_accrued_bill":pk_accrued_bill,
                "pk_tradetype":pk_tradetype
            };
            console.log("制单按钮参数："+makebillArr);
            requestApi.makebill({
                data:makebillArr,
                success:(data)=>{
                console.log("后台制单逻辑响应参数"+data);
                let srccode = "erm" + data.cachekey;
                cacheTools.set("erm" + data.cachekey, data.pklist);
                //跳转
                props.openTo(data.url, {
                    status: 'edit',
                    appcode: data.appcode,
                    pagecode: data.pagecode,
                    pagekey:'',
                    ifshowQuery:true,
                    n: '凭证生成',//'凭证生成'
                    scene: srccode
                });
                
                },
                error:(data)=>{
                    toast({ content: data.message, color: 'danger' });
                }
            });

        }
    
    }
}

/*
 * @method   if条件下为false   除去NaN、0、-0、false   剩余undefined、null、""
 * @author   add by yangguoqiang @18/03/19
 * @params
 *     condition     {any}
 * @return   {boolean}       返回ture/false
 * @demo     isWrong('')    因为后台返回数据不规范
 */
function isWrongFalse(param) {
    return typeof param === 'undefined' || param === null || param === '' || param === false;
}

export { pageButtonClick };

// 1903方式，参数列表在url中，改为根据url的page属性从session中获取
// function getRequest1(url) {
//     if (!url)
//         url = document.location.search;
//     var theRequest = new Object();
//     if (url.indexOf("?") != -1) {
//         var str = url.substring(url.indexOf("?") + 1);
//         var strs = str.split("&");
//         for (var i = 0; i < strs.length; i++) {
//             theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
//         }
//     }
//     return theRequest;
// }
// xuzd5 适配到1909
function getRequest1(url) {
    if (!url)
        url = document.location.search;
    let sessionInfo = ""
    if (url.indexOf("page=") != -1) {
        //获取url中页面page参数 1909url中参数仅有page
        var page;
        if (url.indexOf("?") != -1) {
            var str = url.substring(url.indexOf("?") + 1);
            var strs = str.split("&");
            page = strs[0].split("=")[1];
        }

        //根据page获取session storage中原来1903url中的参数
        var msg = getGlobalStorage('sessionStorage', 'NCCAPPURL');
        msg = JSON.parse(msg);
        sessionInfo = msg[page];
    } else if (url.indexOf("?") != -1) {
        sessionInfo = url.substring(url.indexOf("?") + 1);        
    } else {
        sessionInfo = url;
    }
    

    //解析参数
    var theRequest = new Object();
    var strs = sessionInfo.split("&");
    for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
    return theRequest;
}